<template>
	<div>
		<el-descriptions
			:column="2"
		>
			<el-descriptions-item label="存储卷名">{{volumeInfo?.rbdName || '-'}}</el-descriptions-item>
			<el-descriptions-item label=""></el-descriptions-item>
			<el-descriptions-item label="元数据池名">{{volumeInfo?.poolName || '-'}}</el-descriptions-item>
			<el-descriptions-item label="数据池名">{{volumeInfo?.dataPoolName || '-'}}</el-descriptions-item>
			<el-descriptions-item label="存储卷用量">{{formatUnits(volumeInfo?.usedSize)}}</el-descriptions-item>
			<el-descriptions-item label="存储卷容量">{{formatUnits(volumeInfo?.totalSize)}}</el-descriptions-item>
			<el-descriptions-item label="存储池可用容量">{{formatUnits(unUsedSize)}}</el-descriptions-item>
		</el-descriptions>
		<el-form
			ref="volumeFormRef"
			label-position="left"
			:model="volumeForm"
			:rules="rules"
			label-width="135x"
			status-icon
		>
			<el-form-item label="扩容后的卷容量(G)" prop="totalSize">
				<el-input v-model="volumeForm.totalSize" />
			</el-form-item>
			<div style="color:#FFC069;padding: 0px 50px;">警告：若重设的存储卷总容量值小于当前存储卷总容量，可能会导致存储卷不可用，请知晓。</div>
		</el-form>
	</div>
</template>

<script lang="ts" setup>
import { ref, reactive, toRefs } from 'vue';
import { VolumeTableRow } from '../index.vue';
import type { FormInstance, FormRules } from 'element-plus';
import { ElMessage } from 'element-plus';
// import { useStorageApi } from '/@/api/storage/index';
import { useBlockStorageApi } from '/@/api/block-storage/index';
import { formatUnits } from '/@/utils/other';

const props = defineProps<{
	volumeInfo: VolumeTableRow | null | undefined
}>();

// 正则验证
const checkRbdSize = (rule:any, value:any, callback:any) => {
	if (!value) {
		return callback(new Error('请输入扩容后的卷容量'));
	}

	if (!/^(0|[1-9]\d*)(\.\d{1,2})?$/.test(value)) {
		return callback(new Error('只能输入正数,且保留2位小数'));
	}
	callback();
};

const { volumeInfo } = toRefs(props);
const unUsedSize = ref('');
// const usedSize = ref('');
const rules = reactive<FormRules>({
	totalSize: [{ required: true, validator: checkRbdSize, trigger: 'blur' }]
});

console.log(props.volumeInfo?.poolName);

useBlockStorageApi().getPool({ 'poolName': props.volumeInfo?.dataPoolName }).then(res => {
	unUsedSize.value = res.data.rbdAvailableCapacity;
	if (parseInt(unUsedSize.value) < 0)unUsedSize.value = '0';
});
// change volume size
const volumeFormRef = ref<FormInstance>();
const volumeForm = reactive<{totalSize:string}>({ totalSize: '' });
const emits = defineEmits(['update:value']);
const submitChange = () => {
	if (!volumeFormRef.value) return;
	volumeFormRef.value?.validate((valid) => {
		if (valid) {
			useBlockStorageApi().updataVolume({
				poolName: volumeInfo.value?.poolName as string,
				rbdName: volumeInfo.value?.rbdName as string,
				rbdSize: volumeForm.totalSize }).then((res:any) => {
				!res.code && ElMessage.success(`添加【扩/缩存储卷${volumeInfo.value?.rbdName}】任务成功`);
				emits('update:value', false);
			});
		}
	});
};

defineExpose({
	submitChange
});
</script>